package com.atfzr.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 望夜
 * @date 2023/8/19---22:37
 * @SuppressWarnings({"all"})
 * 可重入锁: 指的是可重复递归调用的锁，在外层使用锁之后，在内层仍然可以使用，并不发生死锁。
 */
public class ReEntryLockDemo {
    public static void main(String[] args) {
//        reEntryM1();
        m3();
    }

    private static  void m3(){
        ReentrantLock lock = new ReentrantLock();

        new Thread(()->{
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t ----come in外层调用");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\t ----come in内层调用");
                } finally {
                    System.out.println(66);
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        },"t1").start();


        new Thread(()->{
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t ----come in外层调用");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\t ----come in内层调用");
                } finally {
                    System.out.println(66);
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        },"t2").start();
    }

    private static void reEntryM1() {
        Object object = new Object();

        //在synchronized 代码块中嵌套synchronized可以 永远得到锁
        new Thread(()->{
            synchronized (object){
                System.out.println(Thread.currentThread().getName() + "\t ----外层调用");
                synchronized (object){
                    System.out.println(Thread.currentThread().getName() + "\t ----中层调用");
                    synchronized (object){
                        System.out.println(Thread.currentThread().getName() + "\t ----内层调用");
                    }
                }
            }
        },"t1").start();
    }
}
